const express = require('express')
const multer = require('multer')
const path = require('path')
const router = express.Router()

const storage = multer.diskStorage({
    destination: (req, file, cb) => { cb(null, 'uploads/') },
    filename: (req, file, cb) => { cb(null, Date.now() + path.extname(file.originalname)) }
})

const upload = multer({ storage: storage })

router.post('/', upload.single('image'), (req, res) => {
    if (!req.file) { return res.status(400).send('没有文件被上传。') }
    const filePath = `http://${process.env.SERVER_HOST}:${process.env.P}/uploads/${req.file.filename}` // 获取文件的访问地址
    res.send({ message: '文件上传成功！', filePath: filePath }) // 返回文件访问地址
})

module.exports = router